<template>
	<view class="scan-code">
		<u-button type="primary" text="扫码" @click="openQrcode" v-if="!isScaning"></u-button>
		<view class="reader-box" v-if="isScaning">
			<view class="reader" id="reader"></view>
		</view>
		<view class="code-info">
			<u--textarea v-model="scanCodeInfo" placeholder="扫码内容" v-if="!isScaning" disabled></u--textarea>
		</view>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	// npm install html5-qrcode // npm 安装
	import {
		Html5Qrcode
	} from 'html5-qrcode'
	export default {
		data() {
			return {
				html5Qrcode: null,
				isScaning: false,
				scanCodeInfo: "",
			}
		},
		methods: {
			openQrcode() {
				this.isScaning = true;
				Html5Qrcode.getCameras().then((devices) => {
					debugger
					if (devices && devices.length) {
						this.html5Qrcode = new Html5Qrcode('reader');
						this.html5Qrcode.start({
								facingMode: 'environment'
							}, {
								focusMode: 'continuous', // 设置连续聚焦模式
								fps: 5, // 设置扫码识别速度
								qrbox: 280 // 设置二维码扫描框大小
							},
							(decodeText, decodeResult) => {
								if (decodeText) { // 这里decodeText就是通过扫描二维码得到的内容
									// console.log("二维码内容：", decodeText)
									this.scanCodeInfo = decodeText
									this.stopScan(); // 关闭扫码功能
								}
							},
							(err) => {
								// console.log(err);  // 错误信息
								uni.showToast({
									title: err,
									icon: 'error',
									duration: 2000, // 提示的延迟时间，单位毫秒，默认：1500
									mask: false, // 是否显示透明蒙层，防止触摸穿透，默认：false
								});
								this.stopScan(); // 关闭扫码功能
							}
						);
					}
				}).catch((err) => {
					let errInfo = err + '';
					console.log("errInfo", errInfo)
					let index = errInfo.indexOf(":")
					let message = errInfo.substring(index + 1, errInfo.length)
					this.$refs.uToast.show({
						message: message,
						position: 'center', // top/bottom
						type: 'error'
					});
					this.stopScan(); // 关闭扫码功能
				});
			},
			stopScan() {
				console.log('停止扫码')
				this.isScaning = false;
				if (this.html5Qrcode) {
					this.html5Qrcode.stop();
				}
			},
		}
	}
</script>

<style scoped>
	.scan-code {
		padding: 20px 10px;
	}

	.reader-box {
		position: fixed;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.reader {
		width: 100%;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.code-info {
		margin-top: 10px;
	}
</style>